<?php
//日本語
class MessagesController extends AppController {

	var $name = 'Messages';
	var $uses = array('User', 'Message');
	var $scaffold;
	var $components = array('AdminAuth', 'Pmaimai', 'RequestHandler', 'Name');
	var $protectedActions = array('index', 'add', 'edit', 'delete');
	var $helpers = array('Html', 'Form');
	
	
	function post($id = null)
	{
		$this->Pmaimai->clean($id);
		$this->Pmaimai->checkMemberAuth();
		
		if(!$id || !is_numeric($id)){
			$this->redirect('/');
		}
		
		$this->set('error', false);
		$userID = $this->Session->read($this->sessionUserName);
		
		$this->User->recursive = 0;
		$user = $this->User->findByIdAndStatus($id, 'active');
		if(!$user){
			$this->flash("送信できません", '/');
			return;
		}
		$this->set('user', $user);
		
		if(!isset($this->data['Message'])){
			return;
		}
		
		if(empty($this->data['Message']['title']) || empty($this->data['Message']['content']) ){
			$this->Message->invalidate('empty', '未入力箇所があります');
		}
		if(!$this->Message->post($userID, $user['User']['id'], $this->data['Message']['title'], $this->data['Message']['content'])){
			$this->set('error', true);
			$this->set('errorMsg', $this->Message->validationErrors);
			return;
		}
		$this->flash(hq($user['User']['nickname'].'さんにメッセージを送信しました'), array('controller' => 'members', 'action' => 'profile'));

	}
	
	function view($id = null)
	{
		$this->Pmaimai->clean($id);
		$this->Pmaimai->checkMemberAuth();
		
		if(!$id || !is_numeric($id)){
			$this->redirect('/');
		}
		
		$this->set('error', false);
		$userID = $this->Session->read($this->sessionUserName);
		$this->User->recursive = 0;
		$user = $this->User->findById($userID);
		$this->set('user', $user);
		
		$message = $this->Message->findById($id);
		$this->set('message', $message);
		if($message['Message']['userto'] === $userID){
			$this->render('viewReceive');
			return;
		}elseif($message['Message']['userfrom'] === $userID){
			$this->render('viewSend');
			return;
		}
		$this->flash("見られません", '/');

	}
	
	
	function receivebox()
	{
		$this->Pmaimai->checkMemberAuth();
		$this->set('error', false);
		$userID = $this->Session->read($this->sessionUserName);
		$this->User->recursive = 0;
		$user = $this->User->findById($userID);
		$this->set('user', $user);
		
		$this->Message->recursive = 0;
		$messages = $this->Message->findAllByUserto($userID);
		$this->set('messages', $messages);

	}
	
	function sendbox()
	{
		$this->Pmaimai->checkMemberAuth();
		$this->set('error', false);
		$userID = $this->Session->read($this->sessionUserName);
		$this->User->recursive = 0;
		$user = $this->User->findById($userID);
		$this->set('user', $user);
		
		$this->Message->recursive = 0;
		$messages = $this->Message->findAllByUserfrom($userID);
		$this->set('messages', $messages);
	}

}
?>